<template>
    <div class="comments-container">
        <h3>发表评论</h3>
        <hr>
        <textarea placeholder="请输入评论内容" maxlength="120" v-model="msg"></textarea>
        <mt-button type="primary" size="large" @click="publish">发表评论</mt-button>
        <div class="comments">
            <div class="comment" v-for="(item, i) in comments" :key="item.add_time">
                <div class="cmt-title">
                    第{{i}}楼&nbsp;&nbsp;用户：{{item.user_name}}&nbsp;&nbsp;发表时间：{{item.add_time | dateFormat}}
                </div>
                <div class="cmt-body">
                    {{item.content}}
                </div>
            </div>
        </div>
        <mt-button type="danger" size="large" plain @click="getMore">加载更多</mt-button>
    </div>
</template>

<script>
    import { Toast } from 'mint-ui'
    export default {
        data(){
            return {
                comments:[],
                pageIndex:1,
                msg:''
            }
        },
        props:['id'],
        created(){
            this.getComments()
        },
        methods:{
            publish(){
                //校验是否为空内容
                if(this.msg.trim().length == 0){
                    Toast('评论内容为空')
                    return
                }
                this.$http.post('api/postcomment/' + this.id,{content: this.msg.trim()}).then(result => {
                    if(result.body.status == 0){
                        this.comments.unshift({
                            user_name:'匿名用户',
                            add_time: (new Date()).toString(),
                            content: this.msg.trim()
                        })
                        this.msg = ''
                    }
                })
            },
            getComments(){
                this.$http.get('api/getcomments/'+ this.id + "?pageIndex=" + this.pageIndex).then(result =>{
                    if(result.body.status == 0){
                        let oldComments = this.comments;
                        this.comments = oldComments.concat(result.body.message)
                    }else{
                        Toast('评论信息加载失败')
                    }
                })
            },
            getMore(){
                this.pageIndex ++;
                this.getComments()
            },
        }
    }
</script>
<style lang="sass" scoped>
    .comments-container{
        h3{
            font-size:16px;
        }
        textarea{
            font-size:14px;
            height:90px;
            margin:0;
        }
        .comments{
            margin:10px 0;

            .comment{
                .cmt-title{
                    background-color:#ccc;
                    font-size:13px;
                    line-height:30px;
                }
                .cmt-body{
                    text-indent:2em;
                    font-size:14px;
                     line-height:40px;
                }
            }
        }
    }
</style>
